package cn.fff.system.controller;

import cn.fff.common.result.Result;
import cn.fff.common.utils.JwtHelper;
import cn.fff.common.utils.MD5;
import cn.fff.model.system.SysUser;
import cn.fff.model.vo.LoginVo;
import cn.fff.system.exception.FffCustomException;
import cn.fff.system.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户登录接口")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;
    // {
    //  "code": 20000,
    //  "data": {
    //    "token":  "admin-token"
    //  }
    //}
    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public Result<?> login(@RequestBody LoginVo loginVo) {
        // 根据 username 查询数据
        SysUser sysUser = sysUserService.getUserInfoByUserName(loginVo.getUsername());
        // 如果查询为空
        if (null == sysUser) {
            throw new FffCustomException(20001, "用户名不存在");
        }
        // 判断密码是否一致
        if(!sysUser.getPassword().equals(MD5.encrypt(loginVo.getPassword()))) {
            throw new FffCustomException(20001, "密码错误");
        }
        // 判断用户是否可用
        if (sysUser.getStatus().equals(0)) {
            throw new FffCustomException(20001, "用户被禁用");
        }
        // 根据 userid 和 username 生成 token 字符串，通过 map 返回
        Map<String, Object> map = new HashMap<>();
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        map.put("token", token);
        return Result.ok(map);
    }

    @ApiOperation("用户详细信息/权限信息获取")
    @GetMapping("/info")
    public Result<?> info(HttpServletRequest request) {
        // 从请求头中获取 token
        String token = request.getHeader("token");
        // 根据 token 获取用户 id
        String userId = JwtHelper.getUserId(token);
        // 根据用户id获取用户信息
        Map<String, Object> map = sysUserService.getUserInfoById(userId);

        return Result.ok(map);
    }
}
